package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"novel_srv/cache"
	"novel_srv/models"
	"time"

	"novel_srv/internal/svc"
	"novel_srv/novel"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListNovelsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListNovelsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListNovelsLogic {
	return &ListNovelsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListNovelsLogic) ListNovels(in *novel.ListNovelsRequest) (*novel.ListNovelsResponse, error) {
	// todo: add your logic here and delete this line

	var n models.Novel
	var novels []models.Novel
	var listNovel []*novel.ListNovels

	key := fmt.Sprintf("list_%d_%d", in.Page, in.PageSie)
	cacheData, _ := cache.Rdb.Get(l.ctx, key).Result()

	if cacheData == "" {
		novels, _ = n.ListNovels(in.Keyword, int(in.Page), int(in.PageSie))
		if len(novels) != 0 {
			jsonData, _ := json.Marshal(novels)
			cache.Rdb.Set(l.ctx, key, jsonData, time.Hour)
		}
	} else {
		json.Unmarshal([]byte(cacheData), &novels)
	}

	for _, nl := range novels {
		list := novel.ListNovels{
			Image:   nl.Image,
			Title:   nl.Title,
			Authors: nl.Authors,
			Types:   nl.Types,
		}
		listNovel = append(listNovel, &list)
	}

	return &novel.ListNovelsResponse{
		List: listNovel,
	}, nil
}

//query := models.DB.Debug()
//if in.Keyword != "" {
//	query = query.Where("title like ? or authors like ? or types like ?",
//		"%"+in.Keyword+"%", "%"+in.Keyword+"%", "%"+in.Keyword+"%")
//}
//if in.Page != 0 {
//
//}
//if in.PageSie != 0 {
//
//}
//query = query.Find(&novels)
